<template>
  <div class="container">
    <div class="table_container">
      <div class="table_title">
        <el-icon color="#409EFC">
          <Histogram />
        </el-icon>
        <span style="margin-left: 1vh">检测列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="检测时间">
            <el-date-picker
                v-model="searchForm.alertDateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="区域名称">
            <el-select
                v-model="searchForm.areaName"
                placeholder="请选择区域"
                clearable
                style="width: 120px"
            >
              <el-option
                  v-for="area in areaOptions"
                  :key="area"
                  :label="area"
                  :value="area"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="处理状态">
            <el-select
                v-model="searchForm.isCheck"
                placeholder="请选择状态"
                clearable
                style="width: 120px"
            >
              <el-option label="已处理" value="是" />
              <el-option label="未处理" value="否" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="table" style="padding-top: 2vh">
        <el-table
            class="el-table-tab"
            :data="alert_data.tableData"
            border
            height="70vh"
            stripe
        >
          <el-table-column label="序号" type="index" width="60" align="center">
            <template #default="scope">
              <span v-text="getIndex(scope.$index)"></span>
            </template>
          </el-table-column>
          <el-table-column prop="alertDate" label="告警时间" width="260" align="center" />
          <el-table-column prop="companyName" label="单位名称" width="220" align="center">
            <template #default="{ row }">
              {{ row.companyName || companyName }}
            </template>
          </el-table-column>
          <el-table-column prop="areaName" label="区域名称" width="200" align="center" />
          <el-table-column prop="isCheck" label="处理状态" width="140" align="center">
            <template #default="{ row }">
              <span v-if="row.isCheck == '是'" style="color: rgb(16, 199, 71)"
              >已处理</span
              >
              <span v-else style="color: red">未处理</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button
                  size="small"
                  type="primary"
                  @click="handlePlay(scope.$index, scope.row)"
              >播放</el-button
              >
              <el-button
                  size="small"
                  type="primary"
                  @click="handleDownload(scope.$index, scope.row)"
              >下载</el-button
              >
              <el-button
                  size="small"
                  type="primary"
                  class="details-btn"
                  @click="showDetails(scope.row)"
              >查看</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-block">
        <el-pagination
            v-model:current-page="alert_data.pageIndex"
            v-model:page-size="alert_data.pageSize"
            :page-sizes="pageSizes"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="alert_data.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- videoDialog -->
    <el-dialog
        v-model="dialogVisible"
        title="告警视频"
        width="40%"
        :before-close="handleClose"
    >
      <video-player
          style="width: 100%"
          class="video-player vjs-custom-skin"
          ref="videoPlayerRef"
          :playsinline="true"
          :options="playerOptions"
      />
    </el-dialog>
  </div>

  <!-- 详情弹窗 -->
  <el-dialog
      title="详情信息"
      v-model="details"
      width="50%"
      top="2vh"
  >
    <div class="details-container">
      <div class="header-background">
        <div class="bird-icon">
        </div>
      </div>

      <div class="details-content">
        <div class="details-title">{{ detailsInfo.title }}</div>
        <div class="details-address">
          {{ detailsInfo.location }}
        </div>
        <div class="details-grid">
          <div class="details-bird">
            <div class="section-header">
              鸟类信息
            </div>
            <div class="bird-type">{{ detailsInfo.birdType }}</div>
          </div>

          <div class="details-description">
            <div class="section-header">
              观测描述
            </div>
            <div class="section-content">{{ detailsInfo.description }}</div>
          </div>

          <div class="details-image">
            <div class="section-header">
              观测照片
            </div>
            <div class="image-container" @click="openImagePreview(detailsInfo.image)">
              <img :src="detailsInfo.image" alt="鸟类观测照片">
              <div class="image-overlay">
              </div>
            </div>
          </div>

          <div class="details-suggestion">
            <div class="section-header">
              保护建议
            </div>
            <div class="section-content">{{ detailsInfo.suggestion }}</div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>

  <!-- 图片预览弹窗 -->
  <el-dialog
      v-model="imagePreviewVisible"
      width="45%"
      @close="closeImagePreview"
  >
    <div class="image-preview-container">
      <img :src="previewImage" alt="鸟类图片预览" class="preview-image">
    </div>
  </el-dialog>


</template>

<script lang="ts" setup>
import {ref, reactive, onMounted, watch, onBeforeUnmount, computed} from "vue";
import "video.js/dist/video-js.css";
import { VideoPlayer } from '@videojs-player/vue';
import { useUserStore } from "@/store/user.js";
import { Histogram } from '@element-plus/icons-vue';
// 导入视频资源
import test1 from "@/assets/video/test1.mp4";
import test2 from "@/assets/video/test2.mp4";
import test3 from "@/assets/video/test3.mp4";
import test4 from "@/assets/video/test4.mp4";
import test5 from "@/assets/video/test5.mp4";
import test6 from "@/assets/video/test6.mp4";

//导入图片资源
import bird1 from '@/assets/bird/10.jpeg';
import bird2 from '@/assets/bird/11.jpeg';
import bird3 from '@/assets/bird/30.jpeg';

// 分页设置
const pageSizes = ref([1, 5, 8, 10]);
const small = ref(false);
const disabled = ref(false);
const background = ref(true);

const dialogVisible = ref(false);
const videoPlayerRef = ref<InstanceType<typeof VideoPlayer> | null>(null);

// 从pinia中获取公司名
const userStore = useUserStore();
const companyName = userStore.companyName;
// 搜索表单
const searchForm = reactive({
  alertDateRange: [],
  areaName: '',
  isCheck: ''
});
// 区域名称选项（去重）
const areaOptions = computed(() => {
  const areas = alert_data.allData.map(item => item.areaName);
  return [...new Set(areas)];
});
// 静态告警数据
const staticAlertData = [
  {
    alertCode: "alert001",
    alertDate: "2025-3-17 08:30:00",
    companyName: "智能鸟类监测公司",
    areaName: "东区湿地",
    videoUrl: test1,
    isCheck: "否",
    title: '机场区域鸟类活动频繁',
    location: '东部机场监测点',
    description: '跑道北侧检测到5只鸟类活动，建议立即驱鸟',
    image: bird1,
    birdType: '池鹭',
    suggestion: '建议启动驱鸟器驱赶'
  },
  {
    alertCode: "alert002",
    alertDate: "2025-3-05 09:15:00",
    companyName: "智能鸟类监测公司",
    areaName: "西区森林",
    videoUrl: test2,
    isCheck: "是",
    title: '农田区域检测到鸟类聚集',
    location: '南部农田监测点',
    description: '3号区域检测到鸟群，可能对作物造成损害',
    image: bird2,
    birdType: '珠颈斑鸠',
    suggestion: '建议铺设覆盖鸟网，避免鸟害'
  },
  {
    alertCode: "alert003",
    alertDate: "2025-2-04 10:20:00",
    companyName: "智能鸟类监测公司",
    areaName: "南区公园",
    videoUrl: test3,
    isCheck: "否",
    title: '保护区发现异常活动',
    location: '西部保护区监测点',
    image: bird3,
    birdType: '乌鸫',
    suggestion: '建议果实套袋，避免鸟类吃食'
  },
  {
    alertCode: "alert004",
    alertDate: "2025-3-17 11:45:00",
    companyName: "智能鸟类监测公司",
    areaName: "北区湖泊",
    videoUrl: test4,
    isCheck: "是"
  },
  {
    alertCode: "alert005",
    alertDate: "2025-3-11 13:10:00",
    companyName: "智能鸟类监测公司",
    areaName: "中心区",
    videoUrl: test5,
    isCheck: "否"
  },
  {
    alertCode: "alert006",
    alertDate: "2025-3-05 14:30:00",
    companyName: "智能鸟类监测公司",
    areaName: "东区湿地",
    videoUrl: test6,
    isCheck: "是"
  },
  {
    alertCode: "alert007",
    alertDate: "2025-3-19 15:45:00",
    companyName: "智能鸟类监测公司",
    areaName: "西区森林",
    videoUrl: test1,
    isCheck: "否"
  },
  {
    alertCode: "alert008",
    alertDate: "2025-3-18 16:20:00",
    companyName: "智能鸟类监测公司",
    areaName: "南区公园",
    videoUrl: test2,
    isCheck: "是"
  }
];

// 从localStorage加载数据或使用静态数据
const loadAlertData = () => {
  const savedData = localStorage.getItem('alertData');
  if (savedData) {
    return JSON.parse(savedData);
  }
  return [...staticAlertData];
};

// 保存数据到localStorage
const saveAlertData = (data) => {
  localStorage.setItem('alertData', JSON.stringify(data));
};

// 告警加分页数据
const alert_data = reactive({
  tableData: [], // 表格数据
  pageIndex: 1, // 默认第一页
  total: staticAlertData.length, // 数据总数
  pageSize: 10, // 默认每页显示10条
  allData: loadAlertData(), // 所有数据，从缓存或静态数据加载
  filteredData: [] // 过滤后的数据
});

// 监听allData变化并保存到localStorage
watch(() => [...alert_data.allData], (newVal) => {
  saveAlertData(newVal);
});

// 每页大小变化
const handleSizeChange = (val) => {
  alert_data.pageSize = val;
  getAlerts();
};

// 当前页变化
const handleCurrentChange = (val) => {
  alert_data.pageIndex = val;
  getAlerts();
};

// 获取告警列表信息
const getAlerts = () => {
  // 应用搜索过滤
  applyFilter();

  const start = (alert_data.pageIndex - 1) * alert_data.pageSize;
  const end = start + alert_data.pageSize;
  alert_data.tableData = alert_data.filteredData.slice(start, end);
  alert_data.total = alert_data.filteredData.length;
};

// 应用搜索过滤
const applyFilter = () => {
  alert_data.filteredData = alert_data.allData.filter(item => {
    // 处理状态过滤
    if (searchForm.isCheck && item.isCheck !== searchForm.isCheck) {
      return false;
    }

    // 区域名称过滤
    if (searchForm.areaName && item.areaName !== searchForm.areaName) {
      return false;
    }

    // 时间范围过滤
    if (searchForm.alertDateRange && searchForm.alertDateRange.length === 2) {
      const startDate = new Date(searchForm.alertDateRange[0]).getTime();
      const endDate = new Date(searchForm.alertDateRange[1]).getTime();
      const alertDate = new Date(item.alertDate).getTime();

      if (alertDate < startDate || alertDate > endDate) {
        return false;
      }
    }

    return true;
  });
};

// 搜索处理
const handleSearch = () => {
  alert_data.pageIndex = 1; // 重置到第一页
  getAlerts();
};

// 重置搜索
const handleReset = () => {
  searchForm.alertDateRange = [];
  searchForm.areaName = '';
  searchForm.isCheck = '';
  handleSearch();
};


// 更新数据中的某一条记录
const updateAlertItem = (alertCode, updates) => {
  const index = alert_data.allData.findIndex(item => item.alertCode === alertCode);
  if (index !== -1) {
    alert_data.allData[index] = { ...alert_data.allData[index], ...updates };
    getAlerts(); // 重新加载当前页数据
  }
};

// 点击播放视频
const handlePlay = (index, row) => {
  // 给dialog框的视频播放器赋值
  playerOptions.sources[0].src = row.videoUrl;
  // 弹出dialog框
  dialogVisible.value = true;
  // 更新告警信息为已处理
  updateAlertItem(row.alertCode, { isCheck: "是" });
};

// 点击下载视频
const handleDownload = (index, row) => {
  // 下载视频
  fetch(row.videoUrl)
      .then((res) => res.blob())
      .then((blob) => {
        const a = document.createElement("a");
        const objectUrl = window.URL.createObjectURL(blob);
        a.download = `告警视频_${row.alertCode}.mp4`;
        a.href = objectUrl;
        a.click();
        window.URL.revokeObjectURL(objectUrl);
        a.remove();
      });
};

// 点击查看详情
const details = ref(false)
const detailsInfo = ref(null)
const showDetails = (item) => {
  console.log(item)
  details.value = true
  detailsInfo.value = item
}

// 图片预览相关状态
const imagePreviewVisible = ref(false)
const previewImage = ref('')


// 打开图片预览
const openImagePreview = (img) => {
  previewImage.value = img
  imagePreviewVisible.value = true
}

// 关闭图片预览
const closeImagePreview = () => {
  imagePreviewVisible.value = false
}


// 获取表格序号
const getIndex = (index) => {
  return (alert_data.pageIndex - 1) * alert_data.pageSize + index + 1;
};

// 定义播放器配置信息
const playerOptions = reactive({
  playbackRates: [0.5, 1.0, 1.5, 2.0],
  autoplay: true,
  muted: false,
  loop: false,
  preload: "auto",
  language: "zh-CN",
  aspectRatio: "16:9",
  fluid: true,
  sources: [
    {
      type: "video/mp4",
      src: "",
    },
  ],
  poster: "",
  notSupportedMessage: "此视频暂无法播放，请稍后再试",
  controls: true,
  controlBar: {
    timeDivider: true,
    durationDisplay: true,
    remainingTimeDisplay: true,
    fullscreenToggle: true,
  },
});

// 关闭dialog时安全销毁播放器资源
const handleClose = (done) => {
  // 安全销毁播放器
  try {
    //@ts-ignore
    if (videoPlayerRef.value && videoPlayerRef.value.player) {
      //@ts-ignore
      videoPlayerRef.value.player.dispose();
    }
  } catch (error) {
    console.error('销毁播放器时出错:', error);
  }

  // 重置播放器源
  playerOptions.sources[0].src = "";

  done();
};

// 在组件卸载前销毁播放器
onBeforeUnmount(() => {
  try {
    //@ts-ignore
    if (videoPlayerRef.value && videoPlayerRef.value.player) {
      //@ts-ignore
      videoPlayerRef.value.player.dispose();
    }
  } catch (error) {
    console.error('组件卸载时销毁播放器出错:', error);
  }
});

onMounted(() => {
  // 获取告警列表信息
  getAlerts();
});
</script>

<style scoped>
.search-container {
  padding: 15px 0;
  border-bottom: 2px solid #ebeef5;
  display: flex;
  justify-content: center;
  align-items: center;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.search-form el-form-item {
  margin-bottom: 0;
  margin-right: 15px;
}

.search-form el-form-item:last-child {
  margin-right: 0;
}

.container {
  width: 100%;
  height: 100%;
  padding: 20px;
  background: linear-gradient(135deg, #e0f7fa, #c8e6c9, #a5d6a7);
}

.table_container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  width: 80%;
  margin: 0 auto;
}

.table_title {
  display: flex;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.table {
  margin-top: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-table-tab {
  width: 90%;
  font-size: 16px;
}

.pagination-block {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 视频播放器样式 */
.video-player {
  border-radius: 8px;
  overflow: hidden;
}

/* 信息详情样式 */
.details-container {
  position: relative;
  border-radius: 15px;
  overflow: hidden;
  background: linear-gradient(to bottom, #f8f9fa, #e9ecef);
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
}

.header-background {
  height: 100px;
  background: linear-gradient(to right, #27ae60, #2ecc71);
  position: relative;
  overflow: hidden;
}

.header-background::before {
  content: "";
  position: absolute;
  top: -50px;
  right: -50px;
  width: 200px;
  height: 200px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
}

.bird-icon {
  position: absolute;
  bottom: -30px;
  left: 50%;
  transform: translateX(-50%);
  width: 70px;
  height: 70px;
  background: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  z-index: 10;
}

.details-content {
  padding: 50px 30px 30px;
  position: relative;
}

.details-title {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  text-align: center;
  margin-bottom: 10px;
}

.details-address {
  text-align: center;
  color: #7f8c8d;
  font-size: 16px;
  margin-bottom: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.details-address i {
  color: #e74c3c;
}

.details-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.details-description,
.details-bird,
.details-suggestion,
.details-image {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
  position: relative;
  overflow: hidden;
}

.details-description:hover,
.details-bird:hover,
.details-suggestion:hover,
.details-image:hover {
  transform: translateY(-5px);
}

.details-description::before,
.details-bird::before,
.details-suggestion::before,
.details-image::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 5px;
  height: 100%;
  background: #27ae60;
}

.section-header {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}


.section-content {
  font-size: 15px;
  color: #34495e;
  line-height: 1.6;
}

.bird-type {
  display: inline-block;
  background: rgba(39, 174, 96, 0.2);
  color: #27ae60;
  padding: 5px 15px;
  border-radius: 20px;
  font-weight: 600;
  margin-bottom: 10px;
}

.image-container {
  position: relative;
  border-radius: 10px;
  overflow: hidden;
  height: 200px;
}

.image-container img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.image-container:hover img {
  transform: scale(1.05);
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-container:hover .image-overlay {
  opacity: 1;
}

/* 图片预览样式 */
.image-preview-container {
  position: relative;
  height: 70vh;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.preview-image {
  margin-top: 20px;
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border-radius: 10px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);
}



/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 10px;
  }

  .table_container {
    padding: 15px;
  }

}
</style>